//
//  LoginViewController.swift
//  mggz
//
//  Created by ShareAnimation on 2017/8/3.
//  Copyright © 2017年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SnapKit
import YYText
import Alamofire

class LoginNavigationController: UINavigationController{
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nil, bundle: nil)
    }
    
    init() {
        super.init(rootViewController: LoginViewController())
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override var childViewControllerForStatusBarStyle: UIViewController? {
        return self.topViewController
    }
}

class LoginViewController: UIViewController {
    var securityAlert:TWLAlertView?
    var codeView:SecondDeviceLoginView?
    
    var currentVasion:String?
    /// 头部的蓝色区域
    var headerView: UIView = {
       let view = UIView()
        view.backgroundColor = colorWith255RGB(16, g: 142, b: 233)
        return view
    }()
    
   fileprivate lazy var switchAccount:UIButton = {
       let switchAccount = UIButton.init(type: UIButtonType.system)
       switchAccount.frame = CGRect.zero
       switchAccount.setTitle("切换到企业", for: UIControlState.normal)
       return switchAccount
    }()
    fileprivate lazy var forgetPassword:UIButton = {
        let forgetPassword = UIButton.init(type: UIButtonType.system)
        forgetPassword.frame = CGRect.zero
        forgetPassword.setTitle("忘记密码?", for: UIControlState.normal)
        return forgetPassword
    }()
    
    
    
    
    /// 用户名
    var usernameTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入手机号码"
        textField.autocorrectionType = UITextAutocorrectionType.no
        textField.autocapitalizationType = .none
        textField.keyboardType = .numberPad
        textField.clearButtonMode = .always
        
        
        let imageView = UIImageView(image: UIImage.init(named: "Icon_手机")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.gray
        imageView.frame = CGRect(x: 0, y: 0, width: 28, height: 22)
        imageView.contentMode = .scaleAspectFit
        
        textField.leftView = imageView
        textField.leftViewMode = .always
        
        return textField
        
    }()
    
    /// 密码
    var passwordTextField: UITextField = {
        let textField = UITextField()
        textField.placeholder = "请输入密码"
        textField.isSecureTextEntry = true
        textField.clearButtonMode = .always
        
        let imageView = UIImageView(image: UIImage.init(named: "ic_lock")!.withRenderingMode(.alwaysTemplate))
        imageView.tintColor = UIColor.gray
        imageView.frame = CGRect(x: 0, y: 0, width: 28, height: 22)
        imageView.contentMode = .scaleAspectFit
        textField.leftView = imageView
        textField.leftViewMode = .always
        
        return textField
    }()
    
    /// 登录按钮
    var loginButton: UIButton = {
        let button = UIButton()
        button.setTitle("登录", for: .normal)
        button.setTitleColor(UIColor.white, for: .normal)
        button.backgroundColor = UIColor(red: 0.06, green: 0.56, blue: 0.91, alpha: 1)
        button.titleLabel?.font = wwFont_Regular(18)
        button.layer.cornerRadius = 5

        return button
    }()
    fileprivate lazy var regiserView:UIView = {
        let regiserView = UIView.init()
        let makeRegisetLabel = UILabel.init(frame: CGRect(x: 0, y: 0, width: 73, height: 30))
        makeRegisetLabel.text = "还没账号?"
        makeRegisetLabel.font = UIFont.systemFont(ofSize: 15)
        regiserView.addSubview(makeRegisetLabel)
        let registerButton = UIButton.init(type: UIButtonType.system)
        registerButton.frame = CGRect(x: 78, y: 0, width: 65, height: 30)
        registerButton.setTitle("免费注册", for: UIControlState.normal)
        registerButton.addTarget(self, action: #selector(doSignUpAction), for: .touchUpInside)
        regiserView.addSubview(registerButton)
        return regiserView
    }()
    
    
//    /// 忘记密码
//    var forgetPasswordLabel: YYLabel = {
//        let label = YYLabel()
//        return label
//    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: .done, target: self, action: #selector(doCancelAction))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "注册", style: .done, target: self, action: #selector(doSignUpAction))
    self.navigationItem.rightBarButtonItem?.setTitleTextAttributes([NSAttributedStringKey.font:UIFont.systemFont(ofSize: 15)], for: .normal)
       // self.registerButton.addTarget(self, action: #selector(doSignUpAction), for: .touchUpInside)
        self.setupCurrentVasionData()
        self.checkAppVasionData()
        let username = LoginAuthenticationService.getLastUsernameAndPassword().0
        let password = LoginAuthenticationService.getLastUsernameAndPassword().1
//        self.usernameTextField.text = "zhangff"
//        self.usernameTextField.text = "13345678227"
//        self.passwordTextField.text = "123456"
        self.usernameTextField.text = username
        self.passwordTextField.text = password

    self.navigationController?.navigationBar.barTintColor = colorWith255RGB(16, g: 142, b: 233)
        self.navigationController?.navigationBar.tintColor = UIColor(white: 1, alpha: 1)
        self.navigationController?.navigationBar.isTranslucent = false
        self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        
        self.setupViews()
        
    }
    
    func setupViews() {
        self.switchAccount.titleLabel?.font = wwFont_Light(15)
        self.switchAccount.addTarget(self, action: #selector(switchAccountClick), for: .touchUpInside)
        self.switchAccount.setTitleColor(colorWith255RGB(16, g: 142, b: 233), for: .normal)
        self.view.addSubview(switchAccount)
        self.switchAccount.snp.makeConstraints { (make) in
            make.right.equalTo(self.view).offset(-10)
            make.bottom.equalTo(self.view).offset(-25)
            make.size.equalTo(CGSize(width: 140, height: 30))
         }
        self.view.addSubview(headerView)
        self.headerView.snp.makeConstraints { (make) in
            make.right.left.equalTo(self.view)
            make.top.equalTo(self.view)
            make.height.equalTo(self.view.bounds.height * 0.32)
        }
        
        //self.headerView.addSubview(self.registerButton)
//        self.registerButton.snp.makeConstraints { (make) in
//            make.top.equalTo(self.headerView).offset(30)
//            make.right.equalTo(self.headerView).offset(-30)
//        }
        let logoImageView = UIImageView()
        logoImageView.image = UIImage(named: "LC_logo")
        logoImageView.contentMode = .scaleAspectFit
        headerView.addSubview(logoImageView)
        logoImageView.snp.makeConstraints { (make) in
            make.center.equalTo(headerView)
        }
        
//        let appLabel = UILabel()
//        appLabel.text = "民工端"
//        appLabel.textColor = UIColor.white
//        appLabel.font = wwFont_Light(15)
//        headerView.addSubview(appLabel)
//        appLabel.snp.makeConstraints { (make) in
//            make.right.equalTo(logoImageView)
//            make.top.equalTo(logoImageView.snp.bottom).offset(10)
//        }
        self.view.addSubview(usernameTextField)
        self.usernameTextField.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(28)
            make.right.equalTo(self.view).offset(-28)
        make.top.equalTo(self.headerView.snp.bottom).offset(36)
            make.height.equalTo(45)
        }
        let grayLine1 = UIView()
        grayLine1.backgroundColor = colorWith255RGB(217, g: 217, b: 217)
        self.view.addSubview(grayLine1)
        grayLine1.snp.makeConstraints { (make) in
           make.top.equalTo(self.usernameTextField.snp.bottom)
            make.left.right.equalTo(self.usernameTextField)
            make.height.equalTo(1)
        }
        
        self.view.addSubview(passwordTextField)
        self.passwordTextField.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.usernameTextField)
            make.top.equalTo(self.usernameTextField.snp.bottom).offset(14)
            make.height.equalTo(self.usernameTextField)
        }
        
        let grayLine2 = UIView()
        grayLine2.backgroundColor = colorWith255RGB(217, g: 217, b: 217)
        self.view.addSubview(grayLine2)
        grayLine2.snp.updateConstraints { (make) in
         make.top.equalTo(self.passwordTextField.snp.bottom)
            make.left.right.equalTo(self.passwordTextField)
            make.height.equalTo(1)
        }
        
        self.forgetPassword.titleLabel?.font = wwFont_Light(15)
        self.forgetPassword.addTarget(self, action: #selector(doForgetPwdAction), for: .touchUpInside)
        self.forgetPassword.setTitleColor(colorWith255RGB(16, g: 142, b: 233), for: .normal)
        self.view.addSubview(self.forgetPassword)
        self.forgetPassword.snp.makeConstraints { (make) in
            make.left.equalTo(self.view).offset(28)
            make.top.equalTo(grayLine2).offset(8)
            make.size.equalTo(CGSize(width: 80, height: 25))
        }
        
        self.loginButton.addTarget(self, action: #selector(doLoginAction), for: .touchUpInside)
        self.view.addSubview(self.loginButton)
        self.loginButton.snp.makeConstraints { (make) in
            make.left.right.equalTo(self.usernameTextField)
            make.top.equalTo(self.passwordTextField.snp.bottom).offset(40)
            make.height.equalTo(40)
        }
        self.view.addSubview(self.regiserView)
        regiserView.snp.makeConstraints { (make) in
        make.top.equalTo(self.loginButton.snp.bottom).offset(10)
            make.centerX.equalTo(self.view)
            make.size.equalTo(CGSize(width: 143, height: 30))
        }
        
        
        //self.view.addSubview(self.forgetPasswordLabel)
//        let myText = NSMutableAttributedString(string: "忘记密码？找回密码")
//        myText.yy_font = UIFont.systemFont(ofSize: 16)
//        myText.yy_alignment = .center
//        myText.yy_setTextHighlight(NSRange.init(location: 5, length: 4), color: colorWith255RGB(16, g: 142, b: 233), backgroundColor: UIColor.lightGray) { (view, text, range, rect) in
//            self.doForgetPwdAction()
//        }
//        self.forgetPasswordLabel.attributedText = myText
//        self.forgetPasswordLabel.snp.makeConstraints { (make) in
//            make.left.right.equalTo(self.usernameTextField)
//            make.bottom.equalTo(self.view).offset(-20)
//        }
    }
    @objc fileprivate func switchAccountClick(){
//        let gmLogin = GMLoginViewController(nibName: "GMLoginViewController", bundle: nil)
//        gmLogin.modalPresentationStyle = .overCurrentContext
//        gmLogin.modalTransitionStyle = .flipHorizontal
//        self.present(gmLogin, animated: true) {
//            
//        }
        
        let contratorLogin = ContractorLoginViewController(nibName: "ContractorLoginViewController", bundle: nil)
        self.present(contratorLogin, animated: true) {
            
        }
    }
    
    @objc func doCancelAction() {
        self.dismiss(animated: true, completion: nil)
    }
    
    @objc func doForgetPwdAction() {
        let forgetVC = ForgetPwdNavigation()
        forgetVC.modalTransitionStyle = .flipHorizontal
        self.present(forgetVC, animated: true, completion: nil)
    }
    
    
    @objc func doLoginAction() {
        guard let username = self.usernameTextField.text, username.count > 0 else {
            WWError("用户名为空")
            return
        }
        guard let password = self.passwordTextField.text, password.count > 0 else {
            WWError("密码为空！")
            return
        }
//        let username = "zhangff"
//        let password = "123456"
//        let username = "18011223344"
//        let password = "112233"
        
        //未认证账户
//        let username1 = "18758361235"
//        let password1 = "123456"
        
        WWBeginLoadingWithStatus("正在登录")
        UserModel.login(username:username, password: password) { (response) in
            if response.success {
                WWEndLoading()
                (UIApplication.shared.delegate as! AppDelegate).setTags(WWUser.sharedInstance.accountId)
                RemoteNotificationModel.registerClient({ (response) in
                    if response.success {
                       
                    }
                    else {
                    }
                })
                LoginType = 1
                let tabbar = WWTabBarController()
          UIApplication.shared.delegate?.window!?.rootViewController = tabbar
                
            }
            else {
                
                
                let returnMessage = response.message
                
                if returnMessage.contains("多个账号"){
                    WWProgressHUD.dismiss()
                    let mutipleAccount = MutipleAccountViewController(nibName: "MutipleAccountViewController", bundle: nil)
                    mutipleAccount.phoneNum = self.usernameTextField.text
                    mutipleAccount.password = self.passwordTextField.text
                    self.present(mutipleAccount, animated: true, completion: {
                        
                    })
                    
                }else if returnMessage == "MultiUserLoginError"{
                 
                    self.getSecurityCodeToCT()
                    
                }else{
                    WWError(response.message)
                }
            }
        }
    }
    
    fileprivate func getSecurityCodeToCT(){
        self.securityAlert = TWLAlertView.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        let securityView = SecondDeviceLoginView.init(frame: CGRect(x: 0, y: 0, width: 290, height: 250))
        securityView.cancelButton.addTarget(self, action: #selector(cancelButtonClick), for: .touchUpInside)
        securityView.securityField.addTarget(self, action: #selector(securityTextFieldClick(_:)), for: .editingChanged)
        securityView.phoneLabel.text = self.usernameTextField.text
        securityView.sureButton.addTarget(self, action: #selector(sureButtonClick), for: .touchUpInside)
        securityView.securityButton.addTarget(self, action: #selector(securityButtonClick), for: .touchUpInside)
        self.codeView = securityView
      self.securityAlert?.initWithCustomView(securityView, frame: CGRect(x: 0, y: 0, width: 290, height: 250))
        let keyWindow = UIApplication.shared.keyWindow
        keyWindow?.addSubview(self.securityAlert!)
    }
    @objc fileprivate func securityTextFieldClick(_ titleF:UITextField){
        self.codeView?.sureButton.isEnabled = true
     self.codeView?.sureButton.backgroundColor = UIColor(red: 0.06, green: 0.56, blue: 0.91, alpha: 1)
      
    }
        
    @objc fileprivate func cancelButtonClick(){
        self.securityAlert?.cancleView()
        
        
    }
    @objc fileprivate func sureButtonClick(){
       // let model = self.itemArray[index!]
        WWProgressHUD.showWithStatus("正在验证...")
        guard let varificationCode = self.codeView?.securityField.text,varificationCode.count > 0 else {
            QWTextonlyHud("未输入验证码", target: self.view)
            return
        }
        var parameter = [String:String].init()
        parameter["flag"] = "agentapply"
        parameter["cellPhoneNumber"] = self.usernameTextField.text
        parameter["verifycode"] = varificationCode
        
        Alamofire.request(VidifySecurityUrl, method: .get, parameters: parameter, headers: nil).responseJSON { (response) in
            if response.result.isSuccess {
                if let dict = response.result.value as? [String: Any] {
                    guard  dict["State"] as! NSString == "OK" else{
                        QWTextonlyHud("验证码错误,请重新输入！", target: self.view)
                        return
                    }
                    WWSuccess("验证码正确")
                 self.securityAlert?.cancleView()
                 self.multiUserLogin()
                }
                
            }
        }
    }
    
    
    fileprivate func multiUserLogin(){
        WWBeginLoadingWithStatus("正在登录")
     UserModel.multiUserErrorlogin(username:self.usernameTextField.text!, password: self.passwordTextField.text!) { (response) in
            if response.success {
                WWEndLoading()
                (UIApplication.shared.delegate as! AppDelegate).setTags(WWUser.sharedInstance.accountId)
                RemoteNotificationModel.registerClient({ (response) in
                    if response.success {
                        
                    }
                    else {
                    }
                })
                
                let tabbar = WWTabBarController()
                UIApplication.shared.delegate?.window!?.rootViewController = tabbar
                
            }
            else {
               WWError(response.message)
            }
        }
    }
    
    

    
    @objc fileprivate func securityButtonClick(){
       self.codeView?.securityButton.startWithTime(60, title: "获取验证码", countDownTitle: "重新发送", mainColor: (self.codeView?.securityButton.backgroundColor!)!, countColor: UIColor.gray)
        UserModel.requestSecurityCode(phoneNumber: self.usernameTextField.text!, flag: FlagType.agentapply) { (response) in
            if response.success {
                #if DEBUG
                    WWInform(response.value ?? "好像是空的")
                #else
                #endif
            }
            else {
                WWInform(response.message)
            }
        }
    }
    
    
    fileprivate func setupCurrentVasionData(){
        let infoDictionary = Bundle.main.infoDictionary
        if let infoDictionary = infoDictionary {
            self.currentVasion = (infoDictionary["CFBundleShortVersionString"] as! String)
        }
    }
    
    fileprivate func checkAppVasionData(){
        
        Alamofire.request(CheckNewVasionUrl, method: .get, parameters: nil, headers: nil).responseJSON { (response) in
             if response.result.isSuccess {
                 if let dict = response.result.value as? [String: Any] {
                    
                    guard let vasionCode :String = dict["VersionCode"] as? String else{
                        return
                    }
                    guard let vasionIsForce : Bool = dict["IsForce"] as? Bool else{
                        return
                    }
                    guard let vasionNum : Int = dict["VersionNum"] as? Int else{
                        return
                    }
                    guard let appPath : String = dict["AppPath"] as? String else{
                        return
                    }
                    if self.currentVasion != vasionCode && vasionNum > 0{
                        if vasionIsForce == true{
                            let alert = UIAlertController(title: "太公民工已更新到最新版本，请前往App Store商店下载，为你带来的不便，敬请谅解！", message: "", preferredStyle: .alert)
                            let gotoAppstore = UIAlertAction(title: "前往下载", style: .default, handler: { (action) in
                                let url = NSURL(string: appPath)
                                UIApplication.shared.openURL(url! as URL)
                                self.present(alert, animated: true, completion: {
                                    
                                })
                            })
                            alert.addAction(gotoAppstore)
                            self.present(alert, animated: true, completion: {
                                
                            })
                        }else{
                            let alert = UIAlertController(title: "太公民工已更新到最新版本，请前往App Store商店下载，为你带来的不便，敬请谅解！", message: "", preferredStyle: .alert)
                            let gotoAppstore = UIAlertAction(title: "前往下载", style: .default, handler: { (action) in
                                let url = NSURL(string: appPath)
                                UIApplication.shared.openURL(url! as URL)
                                self.present(alert, animated: true, completion: {
                                    
                                })
                            })
                            let refuseApp = UIAlertAction(title: "残忍拒绝", style: .cancel, handler: { (action) in
                                
                            })
                            refuseApp.setValue(UIColor.gray, forKey: "titleTextColor")
                            alert.addAction(gotoAppstore)
                            alert.addAction(refuseApp)
                            self.present(alert, animated: true, completion: {
                                
                            })
                        }
                    }
                 }else{
                    
                }
             }else{
                
            }
        }
    }
    
    @objc func doSignUpAction() {
        let nav = RegisterNavigation()
        nav.modalTransitionStyle = .flipHorizontal
        self.present(nav, animated: true, completion: nil)
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }

}

